<?php
namespace control;
/*
*往来单位余额表类
*/

class currentUnitBalanceClass extends adIndexClass
{
    private const page = 'currentUnitBalance';
    private const title = '往来单位余额表';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'code'          => [
                        'name'  => "往来单位编码",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => '名称',
                        'width' => 300,
                    ],
                    'nature'         => [
                        'name'  => '往来单位性质',
                        'width' => 300,
                    ],
                    'recMoney'          => [
                        'name'  => '应收款余额('.static::$unit.')',
                        'width' => 300,
                    ],
                    'payMoney'          => [
                        'name'  => '应付款余额('.static::$unit.')',
                        'width' => 300,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "往来单位编码" => text(array("name" => "orderNo")),
                    "名称"   => text(array("name" => "name")),
                    '往来单位性质' => select(array("name" => "type", 'option'=>['客户','供应商'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {

        $clientWhere  = "coid='".self::$coid."'";
        $supplierWhere = "coid='".self::$coid."'";
        if ($this->post('orderNo')){
            $clientWhere.=" and orderNo like '%".$this->post('orderNo')."%'";
            $supplierWhere.=" and code like '%".$this->post('orderNo')."%'";
        }
        if ($this->post('name')){
            $clientWhere.=" and companyName like '%".$this->post('name')."%'";
            $supplierWhere.=" and name like '%".$this->post('name')."%'";
        }
        if ($this->post('type')=='客户'){
            $supplierWhere.=" and 1!=1";
        }elseif ($this->post('type')=='供应商'){
            $clientWhere.=" and 1!=1";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'code',
            "sort" => $this->post('list_sort') ?: "asc",
            "array"   => array(),
        ));
        $page = $this->page([
            "table" => "kehu where {$clientWhere}  UNION select id,code,name,'供应商' as nature from supplier",
            'field' => "khid as id,orderNo as code,companyName as name,'客户' as nature",
            "where" => $supplierWhere,
            'union' => "select ifnull(count(khid),0) as num from kehu where {$clientWhere} UNION select ifnull(count(id),0) as num from supplier where ".$supplierWhere,
            "order" => $orderBy['orderBy'],
        ]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            $money = find(array('table'=>'record','where'=>"typeId = '$array[id]' and coid = '".self::$coid."'",'sum'=>"money"));
            if ($array['nature']=='供应商'){
                //全部转为整数理解
                $payMoney = -$money;
                $recMoney = 0;
            }else{
                $recMoney = $money;
                $payMoney = 0;
            }
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'recMoney':
                        $row[] = $recMoney;
                        break;
                    case 'payMoney':
                        $row[] = abs($payMoney)==0?0:$payMoney;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $rec = find([
            'table'  => "record",
            'single' => " coid = '".self::$coid."' and typeId in (select khid from kehu where {$clientWhere})",
            'field'  => "ifnull(sum(money),0)money ",
        ]);
        $pay = find([
            'table'  => "record",
            'single' => " coid = '".self::$coid."' and typeId in (select id from supplier where {$supplierWhere})",
            'field'  => "ifnull(sum(money),0)money ",
        ]);
        $total    = [
            'recMoney'        => self::formattingFigure($rec['money']),
            'payMoney'   => self::formattingFigure(-$pay['money']),
        ];
        //返回
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = "您还没有导出的权限";
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $clientWhere = "khid in ('".implode("','", $checkedId)."') ";
                $supplierWhere = "id in ('".implode("','", $checkedId)."') ";
                $result = $this->page([
                    "table" => "kehu where {$clientWhere}  UNION select id,code,name,'供应商' as nature from supplier",
                    'field' => "khid as id,orderNo as code,companyName as name,'客户' as nature",
                    "where" => $supplierWhere,
                    'union' => "select ifnull(count(khid),0) as num from kehu where {$clientWhere} UNION select ifnull(count(id),0) as num from supplier where ".$supplierWhere,
                    "order" => "code asc",
                ])['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $money = find(array('table'=>'record','where'=>"typeId = '$array[id]'",'sum'=>"money"));
                if ($array['nature']=='供应商'){
                    //全部转为整数理解
                    $payMoney = -$money;
                    $recMoney = 0;
                }else{
                    $recMoney = $money;
                    $payMoney = 0;
                }
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '往来单位编码'=>$array['code'],
                            '名称'=>$array['name'],
                            '往来单位性质'=>$array['nature'],
                            '应收款余额'=>$recMoney,
                            '应付款余额'=>abs($payMoney)==0?0:$payMoney,
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了往来单位余额表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "往来单位余额表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'往来单位编码',
                    'aliasName'=>'往来单位编码',
                ],
                [
                    'columnName'=>'名称',
                    'aliasName'=>'名称',
                ],
                [
                    'columnName'=>'往来单位性质',
                    'aliasName'=>'往来单位性质',
                ],
                [
                    'columnName'=>'应收款余额',
                    'aliasName'=>'应收款余额(元)',
                ],
                [
                    'columnName'=>'应付款余额',
                    'aliasName'=>'应付款余额(元)',
                ],
            ]
        };
    }
}

